package com.xiaogao.centerEdu.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.sun.deploy.net.URLEncoder;
import com.xiaogao.centerEdu.entity.UcenterMember;
import com.xiaogao.centerEdu.service.UcenterMemberService;
import com.xiaogao.centerEdu.utils.ConstantPropertiesUtil;
import com.xiaogao.centerEdu.utils.HttpClientUtils;
import com.xiaogao.commonUtils.JwtUtils;
import com.xiaogao.serviceBase.utils.exceptionHandler.XiaoGaoException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 小高
 * @createtime 2021-06-28-14:59
 * @description
 */
//@CrossOrigin
@Controller
@RequestMapping("/api/ucenter/wx")
public class WxApiController {

    @Autowired
    private UcenterMemberService memberService;

    // 生成微信二维码
    @GetMapping("/login")
    public String genQrConnect(HttpSession session) {
        // 1.微信开放平台授权baseUrl %s相当于占位符
        String baseUrl = "https://open.weixin.qq.com/connect/qrconnect" +
                "?appid=%s" +
                "&redirect_uri=%s" +
                "&response_type=code" +
                "&scope=snsapi_login" +
                "&state=%s" +
                "#wechat_redirect";
        // 需要对redirect_uri进行urlEncode编码
        String redirectUrl = ConstantPropertiesUtil.WX_OPEN_REDIRECT_URL;
        try {
            redirectUrl = URLEncoder.encode(redirectUrl, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
            throw new XiaoGaoException(20001, e.getMessage());
        }
        // 往%s里面赋值
        String url = String.format(baseUrl, ConstantPropertiesUtil.WX_OPEN_APP_ID, redirectUrl, "xiaogao");
        //重定向到请求微信地址里面
        return "redirect:" + url;
    }

    /**
     * 获取扫描人信息，添加数据
     *
     * @param code  类似于手机验证码，随机唯一的值
     * @param state 原样传递
     * @return
     */
    @GetMapping("/callback")
    public String callback(String code, String state) {
        try {
            // 得到授权临时票据code
//        System.out.println("code = " + code);
//        System.out.println("state = " + state);

            // 从redis中将state获取出来，和当前传入的state作比较
            // 如果一致则放行，如果不一致则抛出异常：非法访问

            // 1、向认证服务器发送请求换取 access_token（访问凭证）
            String baseAccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" +
                    "?appid=%s" +
                    "&secret=%s" +
                    "&code=%s" +
                    "&grant_type=authorization_code";
            // 拼接参数
            String accessTokenUrl = String.format(baseAccessTokenUrl,
                    ConstantPropertiesUtil.WX_OPEN_APP_ID,
                    ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                    code);
            // 2、使用httpclient发送请求，得到返回结果
            String result = HttpClientUtils.get(accessTokenUrl);
            System.out.println("accessToken=" + result);
            // 解析json，从result字符串获取出两个值：access_token 和 openid

            // 方式一：gson获取
            // result字符串转换为map集合，根据map里面的key获取对应的值
//        Gson gson = new Gson();
//        HashMap map = gson.fromJson(result, HashMap.class);
//        String accessToken = (String) map.get("access_token");
//        String openId = (String) map.get("openid");

            // 方式二：fastjson获取
            JSONObject json = JSONObject.parseObject(result);
            String access_token = (String) json.get("access_token");
            String openid = (String) json.get("openid");

            // 查询数据库当前的用户是否曾今使用过微信
            UcenterMember member = memberService.getByOpenid(openid);
            if (member == null) {
                // 3、访问微信的资源服务器，获取用户信息
                String baseUserInfoUrl = "https://api.weixin.qq.com/sns/userinfo" +
                        "?access_token=%s" +
                        "&openid=%s";
                String userInfoUrl = String.format(baseUserInfoUrl, access_token, openid);
                String resultUserInfo = HttpClientUtils.get(userInfoUrl);
                // 解析json，获取扫码人的信息
                JSONObject mumberInfo = JSONObject.parseObject(resultUserInfo);
                String nickname = (String) mumberInfo.get("nickname"); // 名称
                String headimgurl = (String) mumberInfo.get("headimgurl"); // 头像
                // 向数据库中插入一条记录
                member = new UcenterMember();
                member.setNickname(nickname);
                member.setOpenid(openid);
                member.setAvatar(headimgurl);
                memberService.save(member);
            }

            // 4、使用jwt根据member对象生成token字符串
            String token = JwtUtils.getJwtToken(member.getId(), member.getNickname());

            // 最后，返回首页面，通过路径传递token字符串
            // 因为端口号不同存在跨域问题，cookie不能跨域
            return "redirect:http://localhost:3000?token="+token;
        } catch (Exception e) {
            throw new XiaoGaoException(20001, "微信扫码登陆失败！");
        }
    }

}
